<template>
  <div class="main">
    <shopHeader :obj="shopData" @changTabName="curNameFn"></shopHeader>
    <van-tree-select
      :items="shops"
      :active-id.sync="cateId"
      :main-active-index.sync="cateIndex"
      height="100%"
      @click-nav="curListFn"
    >
      <template #content>
        <header>
          <div>
            <span>{{ shops[cateIndex] && shops[cateIndex].name }}</span
            ><em>{{ shops[cateIndex] && shops[cateIndex].description }}</em>
          </div>
          <div class="tisp">···</div>
        </header>
        <div v-for="item in goodsList" :key="item.id">
          <van-card
            :tag="
              (item.attributes &&
                item.attributes[0] &&
                item.attributes[0].icon_name.indexOf('新') != -1) ||
              (item.attributes[1] &&
                item.attributes[1].icon_name.indexOf('新') != -1)
                ? '新'
                : ''
            "
            :price="item.specfoods && item.specfoods[0].price + '.00'"
            :desc="item.description"
            :title="item.name"
            :thumb="baseURL + '/img/' + item.image_path"
            @click="goGoods(item)"
          >
            <template #tags>
              <p class="sale">
                {{ item.tips }}
              </p>
              <van-tag plain type="danger" v-if="item.activity">{{
                item.activity.image_text
              }}</van-tag>
              <van-tag
                v-if="
                  (item.attributes &&
                    item.attributes[0] &&
                    item.attributes[0].icon_name.indexOf('招牌') != -1) ||
                  (item.attributes[1] &&
                    item.attributes[1].icon_name.indexOf('招牌') != -1)
                "
                class="signature"
                plain
                type="danger"
                >招牌</van-tag
              >
            </template>
            <template #num>
              <van-button
                v-if="item.specifications.length >= 1"
                type="info"
                @click="chooseAttrFn(item)"
                @click.native.stop
                >选规格</van-button
              >
              <van-stepper
                v-else
                v-model="item.num"
                disable-input
                min="0"
                :show-minus="item.num >= 1"
                :show-input="item.num >= 1"
                @click.native.stop
                @change="changeNum(item)"
                @plus="numCk"
                @minus="numCk"
              />
            </template>
          </van-card>
        </div>
      </template>
    </van-tree-select>
    <van-dialog
      v-model="isShow"
      :title="shopAttribute.name"
      show-cancel-button
      v-if="shopAttribute.specifications"
      :showConfirmButton="false"
      :showCancelButton="false"
      :closeOnClickOverlay="true"
    >
      <div class="content">
        <div class="info">
          <p>
            {{
              shopAttribute.specifications &&
              shopAttribute.specifications[0].name
            }}
          </p>
          <van-button
            plain
            type="info"
            v-for="(item, index) in shopAttribute.specfoods"
            :key="index"
            :class="{ curButton: item.specs[0].checked }"
            @click="changeFn(index)"
            >{{ item.specs[0].value }}</van-button
          >
        </div>
        <div class="footer">
          <span class="price"><em>￥</em>{{ attr_price }}</span>
          <van-button color="#3199e8" @click="addCarFn">加入购物车</van-button>
        </div>
      </div>
    </van-dialog>
    <shopFooter @showCarFn="showCarListFn" :total="total"></shopFooter>
    <van-action-sheet v-model="shopCarListShow">
      <header>
        <div class="title">购物车</div>
        <div class="close"><van-icon name="delete-o" />清空</div>
      </header>
      <div class="content">
        <div class="item" v-for="item in carList" :key="item.id">
          <div class="title">
            <p>{{ item.name }}</p>
            <p class="note">{{ item.specs ? item.specs : "默认" }}</p>
          </div>
          <div class="price"><em>￥</em>{{ item.price }}</div>
          <van-stepper disable-input min="0" v-model="item.num" />
        </div>
      </div>
    </van-action-sheet>
  </div>
</template>

<script>
import { getCategory } from "@/api/shops";
import { shop } from "@/api/shop";
import axios from "@/utils/request";
import shopFooter from "@/components/shopFooter";
import shopHeader from "@/components/shop-header";
export default {
  components: {
    shopFooter,
    shopHeader,
  },
  data() {
    return {
      cateId: 1, //分类id
      cateIndex: 0, //分类索引
      type: 2, //选规格还是选数量
      shopId: this.$route.query.id, //店铺id
      shops: [], //食品种类数据
      goodsList: [], //商品列表
      baseURL: axios.defaults.baseURL,
      isShow: false,
      shopAttribute: [], //商品规格
      attr_price: 0, //商品规格价格
      shopCarListShow: false, //购物车商品列表
      getCar: JSON.parse(localStorage.getItem("buyCar")) || {},
      carList: [], //购物车列表数据
      total: {
        price: 0,
        packing_fee: 0,
      }, //商品总价
      shopData: {}, //商铺信息
      tabName: 0,
      isCk: false,
    };
  },
  created() {
    getCategory(this.shopId).then((res) => {
      //数据加工
      res.data.category_list.map((item) => {
        return (item.text = item.name);
      });
      this.shops = res.data.category_list;
      this.goodsListFn(); //商品列表渲染
      this.totalFn();
    });
    //获取商铺信息
    shop(this.shopId).then((res) => {
      this.shopData = res.data;
    });
  },
  methods: {
    numCk() {
      this.isCk = true;
    },
    curNameFn(val) {
      this.tabName = val;
    },
    //底部价格渲染
    totalFn() {
      this.total.price = 0;
      this.total.packing_fee = 0;
      this.carList.map((item) => {
        this.total.price += item.price * item.num;
        this.total.packing_fee += item.packing_fee * item.num;
      });
    },
    // 跳转到详情页面
    goGoods(item) {
      this.$router.push({
        path: "/goods",
        query: {
          price: this.total.price,
          packing_fee: this.total.packing_fee,
          id: item.item_id,
          obj: item,
        },
      });
    },
    //购物车数据解构
    carData() {
      let carData = this.getCar;
      this.carList = [];
      if (carData) {
        for (let k in carData) {
          for (let k2 in carData[k]) {
            for (let k3 in carData[k][k2]) {
              for (let k4 in carData[k][k2][k3]) {
                this.carList.push(carData[k][k2][k3][k4]);
                this.goodsList.map((item) => {
                  if (item.specfoods[0].food_id == carData[k][k2][k3][k4].id) {
                    if (item.specfoods.length > 1) {
                      item.specfoods.map((item2) => {
                        if (item2.food_id == carData[k][k2][k3][k4].id) {
                          return (item2.num = carData[k][k2][k3][k4].num);
                        }
                      });
                    }
                    return (item.num = carData[k][k2][k3][k4].num);
                  }
                });
              }
            }
          }
        }
      }
    },
    //商品渲染
    goodsListFn() {
      this.shops[this.cateIndex].foods.map((item) => (item.num = 0));
      this.goodsList = this.shops[this.cateIndex].foods;
      this.carData(); //购物车数据解构
    },
    //点击分类切换内容
    curListFn() {
      this.isCk = false;
      this.goodsListFn(); //商品列表渲染
    },
    //选择规格
    chooseAttrFn(shop) {
      this.isShow = true;
      this.shopAttribute = shop;
      this.attr_price = this.shopAttribute.specfoods[0].price;
      this.shopAttribute.specfoods.map((item) => {
        return (item.specs[0].checked = false);
      });
      this.shopAttribute.specfoods[0].specs[0].checked = true;
    },
    //改变规格
    changeFn(index) {
      this.shopAttribute.specfoods.map(
        (item) => (item.specs[0].checked = false)
      );
      this.shopAttribute.specfoods[index].specs[0].checked =
        !this.shopAttribute.specfoods[index].specs[0].checked;
      this.attr_price = this.shopAttribute.specfoods[index].price;
      this.$forceUpdate();
    },
    //改变商品数量
    changeNum(shop) {
      this.addShopCar(shop); //加入购物车
      this.carData(); //购物车数据解构
      this.totalFn(); //底部价格渲染
      this.$forceUpdate();
    },
    //显示购物车列表
    showCarListFn() {
      this.shopCarListShow = !this.shopCarListShow;
    },
    //点击加入购物车
    addCarFn() {
      this.shopAttribute.specfoods.map((item) => {
        if (item.specs[0].checked) {
          item.num = item.num ? item.num : 0;
          item.num++;
          this.addShopCar(item, true); //加入购物车
          this.$toast.success("加入购物车成功");
          this.carData(); //购物车数据解构
          this.totalFn(); //底部价格渲染
          this.isShow = false;
        }
      });
    },
    //加入购物车
    addShopCar(shop, isAttr = false) {
      if (this.isCk) {
        console.log(shop.num);
        let shopId = this.shopId; //商铺id
        let cateId = this.shops[this.cateIndex].id; //分类id
        let itemId = isAttr ? shop.item_id : shop.specfoods[0].item_id; //未知id
        let foodId = isAttr ? shop.food_id : shop.specfoods[0].food_id; //食品id
        let carList = this.getCar; //购物车数据
        carList[shopId] = carList[shopId] ? carList[shopId] : {};
        carList[shopId][cateId] = carList[shopId][cateId]
          ? carList[shopId][cateId]
          : {};
        carList[shopId][cateId][itemId] = carList[shopId][cateId][itemId]
          ? carList[shopId][cateId][itemId]
          : {};
        carList[shopId][cateId][itemId][foodId] = {
          id: foodId, //食品id
          name: shop.name, //食品名称
          num: shop.num, //购买数量
          packing_fee: isAttr
            ? shop.packing_fee
            : shop.specfoods[0].packing_fee, //包装费
          price: isAttr ? shop.price : shop.specfoods[0].price, //价格
          sku_id: isAttr ? shop.sku_id : shop.specfoods[0].sku_id, //规格id
          specs: isAttr ? shop.specs_name : "", //规格
          stock: isAttr ? shop.stock : shop.specfoods[0].stock, //库存
        };
        localStorage.setItem("buyCar", JSON.stringify(carList));
        this.$toast.success("加入购物车成功");
      }
    },
  },
};
</script>

<style lang="less" scoped>
.van-action-sheet {
  bottom: 44px;
  border-radius: 0;
  header {
    height: 44px;
    line-height: 44px;
    display: flex;
    justify-content: space-between;
  }
  .content {
    .item {
      display: flex;
      justify-content: space-between;
      height: 50px;
      line-height: 50px;
      margin: 10px 0;
      .title {
        p {
          height: 20px;
          line-height: 20px;
        }
        .note {
          font-size: 12px;
        }
      }
      .price {
        flex: 1;
        text-align: right;
        color: #ff6600;
        font-weight: 700;
        margin-right: 20px;
        em {
          font-size: 12px;
          font-weight: 400;
        }
      }
    }
  }
}
.main {
  height: 100%;
  overflow: hidden;
}
.van-tree-select {
  padding-bottom: 44px;
  margin-top: 195px;
}
header {
  height: 50px;
  line-height: 50px;
  background-color: #f5f5f5;
  display: flex;
  justify-content: space-between;
  padding: 0 10px;
  span {
    font-size: 22px;
    font-weight: 700;
    color: #737373;
    padding-right: 10px;
  }
  em {
    font-size: 12px;
    color: #666;
  }
  .tisp {
    color: #555;
  }
}
.sale {
  padding: 6px 0;
  em {
    padding-right: 4px;
  }
}
.content {
  padding: 0 10px;
  .info {
    padding-bottom: 20px;
    border-bottom: 1px solid #eee;
    p {
      color: #666;
      padding: 10px 0;
    }
    .van-button {
      margin-right: 10px;
      border: 1px solid #ccc;
      color: #666;
      padding: 10px;
    }
    .curButton {
      border: 1px solid #3199e8;
      color: #3199e8;
    }
  }
}
.van-dialog {
  border-radius: 6px;
}
.footer {
  margin: 10px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 3000;
  .price {
    color: #ff6204;
    font-weight: 700;
    em {
      font-size: 12px;
      font-weight: 400;
    }
  }
  .van-button {
    height: 30px;
    line-height: 30px;
  }
}
.van-button {
  height: 24px;
  line-height: 24px;
  padding: 0 6px;
  border-radius: 4px;
  font-size: 13px;
}
.signature {
  position: absolute;
  top: 0;
  right: 0;
}
.van-card__price {
  color: #ff6600;
}
.van-tree-select__nav {
  width: 90px;
  flex: none;
}
.van-card__title {
  font-weight: 700;
  font-size: 16px;
}
.van-tag--danger.van-tag--plain {
  color: #ff6600;
  border-radius: 20px;
}
.van-card__thumb {
  width: 47px;
  height: 47px;
}
.van-card__bottom {
  margin: 4px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 20px;
}
.van-card__tag {
  top: -8px;
  left: -15px;
}
.van-tag--mark {
  background-color: #4cd964;
}
/deep/.van-stepper__input {
  background-color: transparent;
}
/deep/.van-stepper__minus,
/deep/.van-stepper__plus {
  border-radius: 50%;
  border: 1px solid #3190e8;
  color: #3190e8;
  width: 18px;
  height: 18px;
}
/deep/.van-stepper__plus {
  color: #fff;
  background-color: #3190e8;
}
/deep/.van-info {
  top: -6px;
  right: -42px;
}
/deep/.van-card {
  background-color: #fff;
  border-bottom: 1px solid #eee;
}
/deep/.van-sidebar-item--select::before {
  width: 3px;
  height: 100%;
  background-color: #3190e8;
}
</style>